package com.SampleListView;

import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;

import com.SampleListView.UserDetailLoader.UserDetailCallback;
import com.db.ColumnsUser;
import com.db.MyDatabase;

public class SampleListView extends ListActivity {
	private static final String TAG = "SampleListView";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
               
        MyDatabase mDatabase = new MyDatabase(getApplicationContext());
        Cursor mCursor = mDatabase.getUserList();
        
        startManagingCursor(mCursor);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item1,
				mCursor, new String[] { ColumnsUser.ID, ColumnsUser.NAME, ColumnsUser.ID},
				new int[] { R.id.id, R.id.name, R.id.desc});
        
        MyListViewBinder mListBinder = new MyListViewBinder(this);
		adapter.setViewBinder(mListBinder);//setViewBinder 를 사용하면 기존 값들은 모두 사라지고 setViewBinder를 통해 새로운 값을 가져야 한다.
		
        setListAdapter(adapter);//현재 리스트에 항목을 출력한다.
        
    }
    
    
	private static class MyListViewBinder implements ViewBinder {
		private Context mContext;
		private UserDetailLoader mDetailLoader;
		
		
		public MyListViewBinder(Context context) {
			mContext = context;
			mDetailLoader = new UserDetailLoader(context);
		}
		
		@Override
		public boolean setViewValue(View view, Cursor c, int columnIndex) {

			switch (view.getId()) {//view 가 가진 고유 아이디 값을 가져온다.
			case R.id.name://id와 name은 현재의 값을 가져온다.
			case R.id.id:
				((TextView)view).setText(c.getString(columnIndex));
				break;
			case R.id.desc://desc 필드는 새로운 모습(?)으로 꾸며준다.
				Log.i(TAG, "setViewValue");

				final String folderID = c.getString(columnIndex);
				final TextView detailView = (TextView)view;
				// 로딩동안  loading text 보여주기
				detailView.setText("loading...");
				
				mDetailLoader.loadDetailAsync(folderID, new UserDetailCallback() {
					@Override
					public void onLoaded(UserInfo folderInfo) {
						if (folderInfo != null)
							detailView.setText(folderInfo.getDetail(mContext));
					}
				});
			}
			
			return true;
		}
	}    
    
    
}